{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.BasicRNNCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_embedded = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_embedded,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_embedded = tf.concat((out_fw, out_bw), 2)\n",
    "        \n",
    "        bi_state = tf.concat((state_fw, state_bw), -1)\n",
    "        encoder_state = tuple([bi_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        decoder_cells = tf.nn.rnn_cell.MultiRNNCell([cells(size_layer) for _ in range(num_layers)])\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                sequence_length = self.Y_seq_len,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = training_helper,\n",
    "                initial_state = encoder_state,\n",
    "                output_layer = dense)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "        self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        predicting_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS)\n",
    "        predicting_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cells,\n",
    "                helper = predicting_helper,\n",
    "                initial_state = encoder_state,\n",
    "                output_layer = dense)\n",
    "        predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "        self.fast_result = predicting_decoder_output.sample_id\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-16-f204a13c49d5>:39: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[ 7041, 18531, 30711,  1739, 12146,  2835,  7798,  2890,  2698,\n",
       "          4719, 18187,  4328, 13869, 31295,  9404, 11027,  2934, 14448,\n",
       "         30491, 27088, 12032, 24876, 19813, 29033, 21136, 22400, 15029,\n",
       "         12060, 25025, 25914, 27492, 24334, 11805,  9301,  7573, 19687,\n",
       "          6376,  3552,  9032, 23418, 16544, 17757,  9092, 29078,  9458,\n",
       "          5691, 19373, 30539, 27605, 19633, 25595, 22955, 23336, 30068,\n",
       "          4279,  4003, 13061, 29064, 30123, 13727,  2609, 12456,  7578,\n",
       "          6108, 17477, 10421, 12575, 18437, 25522, 25121, 22630, 21740],\n",
       "        [17956,  3084,  1602, 11595, 18838, 11749, 19924, 10231,  1185,\n",
       "         15923,  7877, 29854,  8062, 14342, 23727, 18701, 25000,  4564,\n",
       "          1755, 13671,  5859, 30610, 29094, 13241, 17423,  6377,  3206,\n",
       "          1816, 29632, 24088, 30386, 16604, 30927,  5336, 20420, 12963,\n",
       "         16035,   826, 15211,    19, 11203,  8852, 29168, 15080,   548,\n",
       "          9467, 27338, 26813, 23767, 26826, 23329,  5731, 12611, 12769,\n",
       "         20602, 29295, 24485, 22562, 31061, 26486, 19587,  6464,  1659,\n",
       "         15537,  7086, 11594,  4456,  7365, 28589, 12069,  5379, 23940],\n",
       "        [24287,  6622, 26697,  5806,  8509, 31323, 25700, 12244, 21479,\n",
       "         29272,  8562,  2417, 16977,   542, 13391, 16581,  5801,  2842,\n",
       "          4594, 31750,  6788, 16642, 29070, 31356,  7956, 15051,  1527,\n",
       "         28689, 19813, 19982,  4048, 18723, 14201,  5397, 10154,  7791,\n",
       "          4996, 26423, 10785, 21109, 15222, 30243, 13574, 23318, 25355,\n",
       "          4995,  8047, 16354, 16466, 17162, 29037, 10959, 23531,  6551,\n",
       "         22921, 28139, 18178,  6177, 25487, 27066, 28978,  6655,  2871,\n",
       "         21418, 28256, 14788, 15964, 26146, 24943, 27779, 29896, 31231],\n",
       "        [ 1213,  2139, 25206, 29848,  2248,  7939, 28622,   127, 23131,\n",
       "         29587, 25165, 22939, 15491, 16739, 26216,  3775,  8442, 25903,\n",
       "          7081,   764,  7104, 26867, 13887,  9999, 10353,  9093,  4827,\n",
       "         24866, 21092, 24444, 26027,  8502, 20754,   573, 11101, 29992,\n",
       "          3484,  8112,   769,  3380, 28716, 30484, 15058, 29557, 26274,\n",
       "          6190, 27913, 23646, 15042,  7784, 24751,  5212,  4825, 11556,\n",
       "          4883, 12557, 26915, 25425,  7602, 15263,  1879, 11413, 22126,\n",
       "         27173,  3384, 17076, 22162, 26013,  9855, 26389,  1812, 11296],\n",
       "        [30213, 18705, 27449,  5694,  7725, 18404, 10356, 16191, 19169,\n",
       "         22948, 18699, 14335, 13199, 25534, 22777,  4945, 18039, 30861,\n",
       "         27505, 15302, 13610, 23905, 26258,  4255, 27012,  5035, 12157,\n",
       "         30397, 13388,  9564,  3450, 29957, 12976, 11828,  2870,  3198,\n",
       "         26318, 29743,  8872, 15142, 26242,    50,  2533,  2260,  5472,\n",
       "          4782, 15399,  9210, 10597, 13652, 10183,   366, 20493, 11648,\n",
       "         25490, 11960, 21872, 22124, 21164, 16082, 25091, 29776,  4667,\n",
       "         27886, 29010, 29926, 15470, 16066,  5632, 15848, 16501, 30455],\n",
       "        [26333, 30670, 16701, 31728,  7357, 27886, 27574, 14845, 23144,\n",
       "         23937, 20931, 31297, 30271,  6269, 16326,  8241, 25022, 19709,\n",
       "         15763,  4113, 25592, 30940, 25789, 17536, 15242, 31987, 30252,\n",
       "         28258, 19332, 21136,  3211, 14415, 22463, 28393,  1782, 28046,\n",
       "         20855, 29400, 24223,  5822, 26327, 13556, 13641, 22655, 29854,\n",
       "          1146, 18503,  7376,  5490,  3884, 21766, 20064, 23732, 28678,\n",
       "          4386,  2537, 19182,  9624, 10661,  4077, 30203,  6496, 22385,\n",
       "          6957, 10980,  2969, 30136,  9747, 31730, 14798, 29781, 31501],\n",
       "        [30689, 30441, 31520, 13662,  4845, 26075, 10535, 10357,  2314,\n",
       "          7810, 31562, 31494,   311, 30786, 26453, 10890, 13866,   585,\n",
       "          5996,  8922, 11751, 23579,  4963,  5381, 12277, 26603, 29692,\n",
       "         20342, 16655, 20177,  5839, 25700,  4736, 30724, 24179, 21867,\n",
       "         20166, 28966, 23898,  7652, 13727, 20743, 14062, 14274, 19401,\n",
       "          1019, 12308,  6800,  7450, 24664, 31500,  7926,  3446, 24319,\n",
       "         25694,  2012, 16689, 11734, 20727, 13891,  5734, 28552, 26659,\n",
       "          5161,  5813,  9338, 13546, 30032, 24671, 31951, 28362, 27494],\n",
       "        [27568,   340, 26866,  1605, 13764, 18107, 18157,  9436,  9747,\n",
       "         30195, 16769, 10958,  3723, 19904, 16105,  2189,  6900, 21155,\n",
       "          9509, 14309,  9634, 12316, 11871, 25243, 16089, 24901, 15244,\n",
       "         26327, 26191, 22777, 27724, 21782, 28035, 18526,  6819, 27298,\n",
       "         25503,  1290, 24602,  6245, 14147,   625,  1287, 18207,  5806,\n",
       "          7557, 11076,  7202, 22972, 30194,  6143, 14564, 11025, 30769,\n",
       "         12232, 11113, 13612, 13336,  9369, 11963, 13693, 25051,  1986,\n",
       "         13564, 24319, 18580, 21078, 16227, 19822, 31061,  7211,  7010],\n",
       "        [22716, 28845, 13280, 17424,  6138, 13170, 31255, 11617,   157,\n",
       "          6402, 11747, 12332, 23219, 15092, 23059, 27819, 29829, 24490,\n",
       "         14225, 20204, 13408, 30356, 16557, 26487, 18706,  5961, 31715,\n",
       "          4781, 19833,  8919, 25509,  2732, 28163, 11171, 21279, 10728,\n",
       "           390,  1085, 12106, 20674, 24696, 27451, 15125, 11452,  3958,\n",
       "           658,  1008, 14455, 22592, 18288, 27654, 17757,  7200, 21822,\n",
       "         12697,   494, 21814, 30800,  4767, 17327,  8675, 18452, 20190,\n",
       "         12228,  5213, 16729,  8452,   975,  7528,  7088,  3076, 15083],\n",
       "        [14037, 12934, 11930, 22488, 27104, 19320,  6705, 15700, 16062,\n",
       "         30604, 27614, 21608, 15224, 26566, 19773, 24901,  6707, 11140,\n",
       "         12413,  9754, 12152, 22577,  4513,  4350, 13905, 23688, 16950,\n",
       "         18915, 10013,  8002, 22765,  5849, 15762, 23161, 24139, 27021,\n",
       "         21783, 21978, 29381, 31546,  6197,  2408, 24289, 29512,  6558,\n",
       "          5445,  1719, 14683,  3961, 19021, 29250, 10375, 20188,  4875,\n",
       "         22831,  4003, 18923,  3571, 16411,  8397, 24353, 24806,   477,\n",
       "         19856, 29000,   619, 31080, 14070,  2010,  9911, 20947, 15563]],\n",
       "       dtype=int32), 10.376687, 0.0]"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:26<00:00,  3.09it/s, accuracy=0.187, cost=5.31]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.75it/s, accuracy=0.199, cost=4.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 6.094989, training avg acc 0.149891\n",
      "epoch 1, testing avg loss 5.148298, testing avg acc 0.200459\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:23<00:00,  3.10it/s, accuracy=0.234, cost=4.69]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.84it/s, accuracy=0.226, cost=4.32]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 4.863626, training avg acc 0.221084\n",
      "epoch 2, testing avg loss 4.732797, testing avg acc 0.230729\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:28<00:00,  3.07it/s, accuracy=0.261, cost=4.32]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.84it/s, accuracy=0.247, cost=4.13]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 4.487107, training avg acc 0.248027\n",
      "epoch 3, testing avg loss 4.561285, testing avg acc 0.247583\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:31<00:00,  3.06it/s, accuracy=0.277, cost=4.09]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.75it/s, accuracy=0.247, cost=4.08]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 4.269172, training avg acc 0.264541\n",
      "epoch 4, testing avg loss 4.518294, testing avg acc 0.253836\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:33<00:00,  3.04it/s, accuracy=0.284, cost=3.92]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.80it/s, accuracy=0.269, cost=4]   \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.123998, training avg acc 0.275203\n",
      "epoch 5, testing avg loss 4.479871, testing avg acc 0.258289\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:33<00:00,  3.04it/s, accuracy=0.294, cost=3.76]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.82it/s, accuracy=0.269, cost=3.95]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.019932, training avg acc 0.283128\n",
      "epoch 6, testing avg loss 4.476587, testing avg acc 0.260980\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:34<00:00,  3.04it/s, accuracy=0.306, cost=3.65]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.80it/s, accuracy=0.29, cost=3.92] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 3.936753, training avg acc 0.289535\n",
      "epoch 7, testing avg loss 4.484711, testing avg acc 0.261932\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:34<00:00,  3.04it/s, accuracy=0.319, cost=3.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.77it/s, accuracy=0.274, cost=3.98]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 3.868007, training avg acc 0.294768\n",
      "epoch 8, testing avg loss 4.497402, testing avg acc 0.261676\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:31<00:00,  3.06it/s, accuracy=0.329, cost=3.42]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.84it/s, accuracy=0.269, cost=3.97]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 3.813459, training avg acc 0.298996\n",
      "epoch 9, testing avg loss 4.509614, testing avg acc 0.262880\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:28<00:00,  3.07it/s, accuracy=0.329, cost=3.37]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.86it/s, accuracy=0.263, cost=4]   \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 3.764877, training avg acc 0.302706\n",
      "epoch 10, testing avg loss 4.537440, testing avg acc 0.261739\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:29<00:00,  3.07it/s, accuracy=0.336, cost=3.3] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.84it/s, accuracy=0.29, cost=4.04] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 3.720549, training avg acc 0.306112\n",
      "epoch 11, testing avg loss 4.539324, testing avg acc 0.263286\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:29<00:00,  3.07it/s, accuracy=0.34, cost=3.21] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.87it/s, accuracy=0.312, cost=3.95]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 3.671926, training avg acc 0.310362\n",
      "epoch 12, testing avg loss 4.551347, testing avg acc 0.264103\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:32<00:00,  3.05it/s, accuracy=0.351, cost=3.22]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.79it/s, accuracy=0.269, cost=4.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 3.639534, training avg acc 0.313105\n",
      "epoch 13, testing avg loss 4.582617, testing avg acc 0.263138\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:31<00:00,  3.06it/s, accuracy=0.349, cost=3.15]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.82it/s, accuracy=0.274, cost=4.17]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 3.607992, training avg acc 0.315521\n",
      "epoch 14, testing avg loss 4.609492, testing avg acc 0.262273\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:30<00:00,  3.06it/s, accuracy=0.37, cost=3.1]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.85it/s, accuracy=0.263, cost=4.16]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 3.581495, training avg acc 0.317952\n",
      "epoch 15, testing avg loss 4.626431, testing avg acc 0.262556\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:31<00:00,  3.06it/s, accuracy=0.362, cost=3.13]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.93it/s, accuracy=0.306, cost=4.03]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.552525, training avg acc 0.320681\n",
      "epoch 16, testing avg loss 4.659593, testing avg acc 0.262065\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:31<00:00,  3.06it/s, accuracy=0.36, cost=3.04] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.84it/s, accuracy=0.285, cost=4.21]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.536075, training avg acc 0.322026\n",
      "epoch 17, testing avg loss 4.667953, testing avg acc 0.261820\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:30<00:00,  3.06it/s, accuracy=0.362, cost=3.07]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.80it/s, accuracy=0.312, cost=4.22]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.529873, training avg acc 0.322200\n",
      "epoch 18, testing avg loss 4.683846, testing avg acc 0.261584\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:30<00:00,  3.06it/s, accuracy=0.377, cost=3.01]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.80it/s, accuracy=0.312, cost=4.23]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.527786, training avg acc 0.321770\n",
      "epoch 19, testing avg loss 4.694051, testing avg acc 0.261892\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [08:31<00:00,  3.06it/s, accuracy=0.377, cost=2.95]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  5.83it/s, accuracy=0.317, cost=4.1] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.473880, training avg acc 0.327499\n",
      "epoch 20, testing avg loss 4.705862, testing avg acc 0.263245\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:17<00:00,  2.24it/s]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.019748569"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from tensor2tensor.utils import bleu_hook\n",
    "\n",
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)\n",
    "    \n",
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])\n",
    "    \n",
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
